<template>
    <div  class="bg">
        <div class="dialogmenu">
            <el-button class="close" @click="close" type="primary">关闭</el-button>
            <el-button class="close2" @click="download" type="primary">代码下载</el-button>
            <el-button class="close4" @click="awaitData" type="primary">同步</el-button>
            <el-button class="close5" @click="awaitdelete" type="danger">删除该页面存储</el-button>
            <div class="flex close3">
                  <el-select v-model="pageValue" @change="changepage" placeholder="请选择预览界面">
                        <el-option
                        v-for="item in globelPage"
                        :key="item.name"
                        :label="item.pagename"
                        :value="item.name">
                        </el-option>
                    </el-select>
            </div>
        </div>
        <!-- <div style="height:100px;"></div> -->
        <div style="position:absolute;height: 100%;margin-top:-100px;"  :style="{width:canvasStyleData.width+'rem',margin:'0 auto',position:'relative'}">
         <div ref="mode" style="height:100%;"  :style="{width:canvasStyleData.width+'rem',margin:'0 auto',position:'relative'}">
            <div class="canvas-container" >
                <div
                    class="canvas"
                    :style="{
                        width: changeStyleWithScale(canvasStyleData.width) + 'rem',
                    }"
                >
                    <ComponentWrapper
                        v-for="(item, index) in componentData"
                        :key="index"
                        :config="item"
                    />
                </div>
            </div>
        </div>
        </div>
    </div>
</template>

<script>
import { getStyle } from '@/utils/style'
import { mapState } from 'vuex'
import ComponentWrapper from './ComponentWrapper'
import { changeStyleWithScale } from '@/utils/translate'

export default {
    components: { ComponentWrapper },
    model: {
        prop: 'show',
        event: 'change',
    },
    data() {
        return {
            globelPage:JSON.parse(localStorage.getItem("GlobalcanvasData")),
            pageValue:''
        }
    },
    props: {
        show: {
            type: Boolean,
            default: false,
        },
    },
    computed: mapState([
        'componentData',
        'canvasStyleData',
    ]),
    mounted(){

    },
    methods: {
        changeStyleWithScale,

        getStyle,
        changepage(e){
            console.log(e)
            let globalData=JSON.parse(localStorage.getItem('GlobalcanvasData'))
            for(let key in globalData){
                    if(globalData[key].name==e){
                        // setComponentData
                        this.$store.commit('setComponentData',globalData[key].canvasData)
                        localStorage.setItem('downloadPage',globalData[key].name)
                         localStorage.setItem('page',globalData[key].name)
                         localStorage.setItem('pageName',globalData[key].pagename)
                    }
            }
        },
       close(){
           this.$emit('change', false)
           this.$emit('closeTK', false)
           this.$router.go(-1)
           setTimeout(() => {
               location.reload()
           },10);

       },
       getMappingValueArrayOfKey(array,keyName){
            if(Object.prototype.toString.call(array)=='[object Array]'){
                return array.map((item,index)=>{
                    return item[keyName]
                })
            }
            return 'null（参数一应为对象数组）';//不是数组
        },
        awaitData(){
          localStorage.setItem('canvasData',JSON.stringify(this.$store.state.componentData))
        },
        awaitdelete(){
          let globalData=JSON.parse(localStorage.getItem('GlobalcanvasData'))
          if(!this.pageValue){
            this.$message.error('请先选择界面!')
            return
          }
            for(let key in globalData){
                    if(globalData[key].name==this.pageValue){
                        // setComponentData
                         globalData.splice(key,1)
                        // this.$store.commit('setComponentData',globalData[key].canvasData)
                         localStorage.setItem('GlobalcanvasData',JSON.stringify(globalData))
                         this.globelPage=globalData
                         this.pageValue=""
                         localStorage.setItem('page',"")
                         localStorage.setItem('downloadPage',"")
                         localStorage.setItem('pageName',"")
                    }
            }
        },
        async download() {
        if(!this.pageValue){
            this.$message.error("请选择下载页面")
            return
        }
            // this.$emit('change', false)
            // console.log(this.$refs.mode)
            // console.log(window)
            // window.document.documentElement.childNodes[0]
            let WalkSwiperList=JSON.parse(localStorage.getItem("WalkSwiperList"))
            let WalkSwiperline=JSON.parse(localStorage.getItem('WalkLineList'))
            let fromKeyList=JSON.parse(localStorage.getItem('fromKeyList'))//submit表单
            let TabSwitchcardList=JSON.parse(localStorage.getItem('TabSwitchcardList'))//tab切换组件
            let TabSwitchcardListImg=JSON.parse(localStorage.getItem('TabSwitchcardListImg'))//tab切换组件
            let MobileHeader=JSON.parse(localStorage.getItem('Mobile_header'))//header
            let Swiperline=[]
            if(WalkSwiperline && WalkSwiperline.length){
                Swiperline=await this.getMappingValueArrayOfKey(WalkSwiperline,'name')
            }
            let strHtml=``
            let submitHtml=``
            let TabSwitchcardHtml=``
            let TabSwitchcardImgHtml=``
            let HeaderHtml=``
            if(MobileHeader){
                 for(let item of MobileHeader){
                    HeaderHtml+=`
                         $("#header_menu>.header_menu_item${item}").click(function() {
                            if($(".menu_children${item}").is(':hidden')){
                                    $(".menu_children${item}").show(200)
                                }else{
                                    $(".menu_children${item}").hide(200)
                                }
                        });

                      `
                 }
            }
            if(TabSwitchcardList){
                 for(let item of TabSwitchcardList){
                    TabSwitchcardHtml+=`
                        $(".${item.Tabclass} li").click(function() {
                        $(this).addClass("TabSwitchcard_active").siblings().removeClass("TabSwitchcard_active");
                        var index = $(this).index();
                    $(this).css({
                        background:'${item.activeBg}'
                    }).siblings().css({
                        background:'#fff'
                    })
                        $(".${item.class} .TabSwitchcard_item").eq(index).fadeTo(600,1).css({display:'block'}).siblings().fadeTo(400,0.4).css({display:'none'})
                    });
                    `
                 }
            }
            if(TabSwitchcardListImg){
                 for(let item of TabSwitchcardListImg){
                    TabSwitchcardImgHtml+=`
                        $(".${item.Tabclass} li").click(function() {
                        $(this).addClass("TabSwitchcard_active").siblings().removeClass("TabSwitchcard_active");
                        var index = $(this).index();
                    $(this).css({
                        color:'${item.activeBg}'
                    }).siblings().css({
                        color:''
                    })
                        $(".${item.class} .TabSwitchcard_item").eq(index).fadeTo(600,1).css({display:'flex'}).siblings().fadeTo(400,0.4).css({display:'none'})
                    });
                    `
                 }
            }
            if(fromKeyList){
            for(let item of fromKeyList){
               submitHtml+=`
                    $("#showSubmitedit").bind("click",function(){
                    $("#showSubmitclose").show()
                    $("#showSubmitedit").hide()
                     $(".lianxi_box").addClass('autolianxi')
                    });
                    $("#showSubmitclose").bind("click",function(){
                    $("#showSubmitclose").hide()
                    $("#showSubmitedit").show()
                    $(".lianxi_box").removeClass('autolianxi')
                    });

         $("#${item}submit").click(function() {
          var d = {};
          var t = $("#${item}").serializeArray();
           let boolType=true
          $.each(t, function() {
          let rule= $(`+`'#${item}'`+`+this.name).attr("rule")
            if(rule){
                if(rule=='validatePhoneReg'&&boolType){
                  let bool=validatePhoneReg(this.value)
                 if(bool){
                        d[this.name] = this.value;
                 }else{
                    boolType=false
                   alert('手机号格式错误！');
                    return
                 }
                }else if(rule=='validateEmail'&&boolType){
                  let bool=validateEmail(this.value)
                  if(bool){
                        d[this.name] = this.value;
                 }else{
                    boolType=false
                   alert('邮箱格式错误！');
                    return
                 }
                }else if(rule=='Notempty'&&boolType){
                  let bool=Notempty(this.value)
                  if(bool){
                        d[this.name] = this.value;
                 }else{
                    boolType=false
                   alert('请输入内容');
                    return
                 }
                }
            }
               d[this.name] = this.value;

          });
          if(boolType){
          $.ajax({
            type: "POST",
            url: localStorage.getItem('baseUrl') + 'web/contactUs',
            data:JSON.stringify(d),
            contentType: 'application/json',
            success: function (res) {
              if(res.code==200){
                alert(res.data)
              }else{
                  alert(res.message)
                }
            }
            })
         }
        });

       `
            }
      }

            if(WalkSwiperList && WalkSwiperList.length){
                for(let item of WalkSwiperList){
                    strHtml+=`
                    new Swiper('.${item.name}', {
                            loop: true,
                            watchSlidesVisibility: true /*避免出现bug*/,
                            slidesPerView: ${Number(item.slidesPerView)},
                            spaceBetween: 10,
                            freeMode: true,
                            slidesPerGroup: ${Number(item.slidesPerView)},
                            observer: true,
                            observeParents: true,
                            loopFillGroupWithBlank: true,
                            //自动切换
                            autoplay: {
                                delay: 0,
                                disableOnInteraction: false,
                            },
                            autoplay: ${item.tabIndex==2?false:true},
                            navigation: {
                                nextEl: '.swiper-button-next',
                                prevEl: '.swiper-button-prev',
                            },
                            speed: ${item.tabIndex==2?600:6000*Number(item.slidesPerView)},
                    })

                    `
                }
            }
            let downloadName=localStorage.getItem('downloadPage')
            const content =String(`
            <!DOCTYPE html>
                <html>
                    <head>`+`
                    <script>
                        (function(doc, win) {
                            var docE1 = doc.documentElement,
                            bodys = document.getElementsByTagName('body')[0],
                                resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
                                recalc = function() {
                                    var clientWidth = docE1.clientWidth;
                                    if (!clientWidth) return;
                                    docE1.style.fontSize = (clientWidth / 375) + 'px';
                                };

                            if (!doc.addEventListener) return;
                            win.addEventListener(resizeEvt, recalc, false);
                            doc.addEventListener('DOMContentLoaded', recalc, false);
                             setTimeout(()=>{
                                console.clear()
                            },1000)
                        })(document, window);
                    <\/script>`+
                    window.document.documentElement.childNodes[0].innerHTML+`
                <meta name="viewport" content="width=device-width,  initial-scale=1.0, maximum-scale=1.0,user-scalable=no">`+
                '</head>'+
            '<body style="opacity:0">'+
            this.$refs.mode.innerHTML+
            `</body>
            <script>

    //初始化swiper
      function swinery(){
          new Swiper(".kerwin", {
            loop: true,
            autoplay: {
                delay: 5000,
                disableOnInteraction: false,
            },

            // 如果需要分页器
            // pagination: {
            //     el: '.swiper-pagination',
            // },

            // 如果需要前进后退按钮
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            }
        })
        }
        window.onload = function () {
            swinery()
            restwalkLineswiper()
        }



    ${strHtml}
    ${submitHtml}
    ${TabSwitchcardHtml}
    ${TabSwitchcardImgHtml}
    $("#header_icon").click(()=>{
         if($("#header_menu").is(':hidden')){
            $('#header_menu').show(250)
        }else{
            $('#header_menu').hide(250)
        }
    })

    ${HeaderHtml}
    function  restwalkLineswiper(){
      let Swiperline='${Swiperline}'.split(",")
      if(Swiperline.length){
        for(let item of Swiperline){
            walkLineswiper(item)
        }
      }
    }
    ${`
        function walkLineswiper(value){
        var bg = document.querySelector('.item-bg');
        var swiper = new Swiper(\`.$`+`{value}\`, {
                effect: 'coverflow',
                grabCursor: true,
                loop: true,
                centeredSlides: true,
                keyboard: true,
                spaceBetween: 0,
                slidesPerView: 'auto',
                speed: 300,
                coverflowEffect: {
                    rotate: 0,
                    stretch: 0,
                    depth: 0,
                    modifier: 3,
                    slideShadows: false
                },
                breakpoints: {
                    480: {
                        spaceBetween: 0,
                        centeredSlides: true
                    }
                },
                simulateTouch: true,
                navigation: {
                    nextEl: \`.news-slider-next$`+`{value}\``+`,
                    prevEl:\`.news-slider-prev$`+`{value}\``+`
                },
                pagination: {
                    el: '.news-slider__pagination',
                    clickable: true
                },
            });
            swiper.on('touchEnd', function () {
                    $('.news__item').removeClass('active');
                    // $('.swiper-slide-active .news__item').addClass('active');
                });
                swiper.on('slideChangeTransitionEnd', function () {
                    $('.news__item').removeClass('active');
                    var activeItem = document.querySelector('.swiper-slide-active');
                    var sliderItem = activeItem.querySelector('.news__item');
                    $(\`.$`+`{value} .swiper-slide-active .news__item\``+`).addClass('active');
                    var x = sliderItem.getBoundingClientRect().left;
                    var y = sliderItem.getBoundingClientRect().top;
                    var width = sliderItem.getBoundingClientRect().width;
                    var height = sliderItem.getBoundingClientRect().height;
                    $('.item-bg').addClass('active');
                    bg.style.width = width + 'px';
                    bg.style.height = height + 'px';
                    bg.style.transform = 'translateX(' + x + 'px ) translateY(' + y + 'px)';
                });
      }`
    }

<\/script>

   <script>
        function getQueryUrlParamVal(name) {
            if (location.href.indexOf("?") == -1 || location.href.indexOf(name + '=') == -1) {
                return '';
            }
            var queryString = location.href.substring(location.href.indexOf("?") + 1);
            queryString = decodeURI(queryString);
            var parameters = queryString.split("&");
            var pos, paraName, paraValue;
            for (var i = 0; i < parameters.length; i++) {
                pos = parameters[i].indexOf('=');
                if (pos == -1) {
                    continue;
                }
                paraName = parameters[i].substring(0, pos);
                paraValue = parameters[i].substring(pos + 1);
                if (paraName == name) {
                    return unescape(paraValue.replace(/\\+/g, " "));
                }
            }
            return '';
        }
        let webUrl=window.location.href
        let parameter=window.location.href.split('?')[1]
        let address=window.location.origin
        let channelNo=getQueryUrlParamVal('channelNo')
        let data={
            webUrl,parameter,address,channelNo
        }
        console.log(data)
        let insertbaseUrl=localStorage.getItem('baseUrl')
            if(data.channelNo){
                $.ajax({
                type: "POST",
                url: insertbaseUrl+'web/insertWebUrl',
                data:JSON.stringify(data),
                contentType: 'application/json',
                })
            }
              document.getElementsByTagName('body')[0].style.opacity=1
              console.clear()
        <\/script>
</html>`)
                //生成报告
                const link = document.createElement("a");
                link.download = downloadName; // 文件名
                link.style.display = "none";
                // 创建文件流
                // 创建bolb实例时，内容一定要放在[]中
                const blob = new Blob([content], { type: "text/html" });
                link.href = window.URL.createObjectURL(blob);
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
        },
    },
}
</script>

<style lang="scss" scoped>
.bg {
    width: 100%;
    height: 100vh;
    top: 0;
    left: 0;
    // position: fixed;
    // background: rgb(0, 0, 0, .5);
    z-index: 10;
    // display: flex;
    align-items: center;
    justify-content: center;
    overflow: auto;
    // padding: 20px;

    .canvas-container {
        // width: calc(100% - 40px);
        height: calc(100%);
        overflow: auto;

        .canvas {
            background: #fff;
            position: relative;
            margin: auto;
        }
    }

    .close {
        position: absolute;
        right: 20px;
        top: 20px;
    }
     .close2 {
        position: absolute;
        right: 100px;
        top: 20px;
    }
      .close3{
        position: absolute;
        right: 200px;
        top: 20px;
    }
      .close4{
        position: absolute;
        right:450px;
        top: 20px;
    }
    .close5{
        position: absolute;
        right:550px;
        top: 20px;
    }
}
.dialogmenu{
    // position: absolute;
    width: 100%;
    height: 100px;
    // z-index: 999999;
    top:0;
    right: 0;
    // background: #fff;
}
</style>
